/**
 * 原料新增或编辑  传入id则为编辑 否则为新增
 * - 重点处理pack_spec，mat_norqgp，mat_brkqgp复合字段，会拆解为val、unit等具体字段与input控件关联
 * - mat_cntrs的特殊处理
 * - AddonAfter字段的特殊处理
 * - 常用单位、包装形式、时间周期 都来自于consts.js
 */

// 页面容器
import { PageContainer } from "@ant-design/pro-layout";
// react控件
import React, { createRef, PureComponent } from "react";
import { history } from "umi"; // 页面跳转
// antd控件
import {
  Form,
  Input,
  Button,
  Select,
  message,
} from "antd";
// 数据接口
import { createNewData, getData } from "@/services/material";
// 获取父页面传来的参数
import { getPageQuery } from "@/utils/utils";
// 通用的常量
import {
  unitOptions,
  packTypeOptions,
  periodOptions,
  storageOptions
} from "@/consts/consts";


const { TextArea } = Input;
const { Option } = Select;

class CreateMat extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      title: "新建原料", // 缺省的页面标题，若为编辑模式 则 会修改
      packUnit: 'ML',  // 新建原料时 的 默认值，编辑模式时来自数据
      norPeriod: '周', // 新建原料时 的 默认值，编辑模式时来自数据
      brkPeriod: '天', // 新建原料时 的 默认值，编辑模式时来自数据

      dataSource: {mat_name: "咖啡粉", mat_brand: "星巴克", pack_spec_type: "罐"}, // 新建原料时 的 默认值，编辑模式时来自数据
    };

    this.creatFromRef = createRef();
  }


  // 页面render后触发获取数据
  componentDidMount() {
    // 若传入id则为编辑模式
    if( getPageQuery().id ){

      this.getEditData().finally(() => {
        console.log("edit data: ", this.state.dataSource)
      });

    }else{
      console.log("create new data")
      // 否则为新建模式
      // 设置一些input的缺省值
      this.creatFromRef.current.setFieldsValue(this.state.dataSource)

    }
  }

  getEditData = async () => {

      // 获取数据
      const {
        data: { ret },
        data: {
          data: { list, total, query }
        }
      } = await getData({ id: getPageQuery().id });
      
      if (ret !== 0 || list.length!=1) {
        return;
      }

      // 将input的默认值设置为当前数据值
      let editData = list[0]

      // 设置AddonAfter控件对应的state变量的默认值
      this.setState({
        packUnit: editData.pack_spec.unit,
        norPeriod: editData.mat_norqgp.unit,
        brkPeriod: editData.mat_brkqgp.unit,
      })

      // 控件的字段与data实际字段的转换
      editData.mat_norqgp_val = editData.mat_norqgp.value
      editData.mat_brkqgp_val = editData.mat_brkqgp.value
      editData.pack_spec_val = editData.pack_spec.value
      editData.pack_spec_type = editData.pack_spec.type

      //根据data设置所有控件当前的值
      this.creatFromRef.current.setFieldsValue(editData)

      this.setState({ dataSource: editData });

  }

  // 新建或编辑后的保存处理
  saveRecord = () => {
    // 获取AddonAfter的输入值
    const { packUnit, norPeriod, brkPeriod } = this.state
    // 验证表单并按照数据结构重组数据
    this.creatFromRef.current.validateFields()
      .then( values => {
        // 对象数据重组
        values.pack_spec = { type: values.pack_spec_type, value: values.pack_spec_val, unit: packUnit }
        values.mat_norqgp = { value: values.mat_norqgp_val, unit: norPeriod }
        values.mat_brkqgp = { value: values.mat_brkqgp_val, unit: brkPeriod }
        
        // 删除界面用到的多余的key
        delete values.mat_norqgp_val
        delete values.mat_brkqgp_val
        delete values.pack_spec_type
        delete values.pack_spec_val

        createNewData(values).then((res) => {
          if(res.data.ret === 0){
            message.success("创建成功！")
            history.push("/matMgt")
          } else {
            message.error("创建失败")
          }
        })

      })
      .catch(errorInfo => {
        /*
        errorInfo:
          {
            values: {
              username: 'username',
              password: 'password',
            },
            errorFields: [
              { name: ['password'], errors: ['Please input your Password!'] },
            ],
            outOfDate: false,
          }
        */
      })
  }

  render() {
    // 获取 几个AddonAfter控件的默认值
    const { packUnit, norPeriod, brkPeriod } = this.state

    // 包装单位input后缀选择
    const unitsAddonAfter = (
      <Select
        onChange={(e) => { this.setState({ packUnit: e }) }}
        value = {packUnit} // 设置缺省值，注意这里一定要用value而非DefaultValue
        className="select-after"
      >
        {unitOptions}
      </Select>
    )
    // 常规存储时间单位后缀选择
    const norPeriodAddonAfter = (
      <Select
        onChange={(e) => { this.setState({ norPeriod: e }) }}
        value = {norPeriod} // 设置缺省值，注意这里一定要用value而非DefaultValue
        className="select-after"
      >
        {periodOptions}
      </Select>
    )
    // 开封存储时间单位后缀选择
    const brkPeriodAddonAfter = (
      <Select
        onChange={(e) => { this.setState({ brkPeriod: e }) }}
        value = {brkPeriod} // 设置缺省值，注意这里一定要用value而非DefaultValue
        className="select-after"
      >
        {periodOptions}
      </Select>
    )

    return (
      /**
       * 最外层的容器必须是PageContaine
       * - title不用管，自动根据routers.ts里面的name出现在页面
       * - 设置footer属性可以出现页面底部的toolbar（fix bottom风格）
       */
      <PageContainer
        footer={[
          <Button key="cancel" onClick={() => {history.push("/matMgt")}}>取消</Button>,
          <Button key="submit" type="primary" onClick={this.saveRecord}>保存</Button>
        ]}
      >
        <div className="ourCard">
          <div className="header">
            <div className="title">基础信息</div>
          </div>
          <div className="content">
            <Form ref={this.creatFromRef} className="flex-form" layout="vertical">
              <Form.Item
                name="mat_name"
                label="原料名称"
                rules={[{ required: true, message: "请输入有效内容" }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="mat_brand"
                label="原料品牌"
                rules={[{ required: false, message: "请输入有效内容" }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="pack_price"
                label="单价"
                rules={[{ required: true, message: "请输入数字" }]}
              >
                <Input type="number" prefix="¥" suffix="RMB" placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="pack_spec_val"
                label="包装规格"
                rules={[{ required: true, message: "请输入数字" }]}
              >
                <Input type="number" addonAfter={unitsAddonAfter} placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="pack_spec_type"
                label="包装形式"
                rules={[{ required: true, message: "请选择" }]}
              >
                <Select>{packTypeOptions}</Select>
              </Form.Item>

              <Form.Item
                name="min_purchase"
                label="起购量"
                rules={[{ required: false, message: "请输入数字" }]}
              >
                <Input type="number" placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="mat_norqgp_val"
                label="常规保质期"
                rules={[{ required: false, message: "请输入数字" }]}
              >
                <Input type="number" addonAfter={norPeriodAddonAfter} placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="mat_brkqgp_val"
                label="开封保质期"
                rules={[{ required: false, message: "请输入数字" }]}
              >
                <Input type="number" addonAfter={brkPeriodAddonAfter} placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="mat_norstg"
                label="常规存储方式"
                rules={[{ required: false, message: "请选择" }]}
              >
                <Select mode="multiple" allowClear placeholder="多种选择">{storageOptions}</Select>
              </Form.Item>

              <Form.Item
                name="mat_brkstg"
                label="开封存储方式"
                rules={[{ required: false, message: "请选择" }]}
              >
                <Select mode="multiple" allowClear placeholder="多种选择">{storageOptions}</Select>
              </Form.Item>

              <Form.Item
                name="fact_name"
                label="厂家名称"
                rules={[{ required: false, message: "请输入有效内容" }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="fact_phone"
                label="厂家联系方式"
                rules={[{ required: false, message: "请输入有效内容" }]}
              >
                <Input type="number" placeholder="请输入" />
              </Form.Item>


              <Form.Item
                name="mat_memo"
                label="备注"
                rules={[{ required: false, message: "请输入有效内容" }]}
              >
                <TextArea
                  placeholder="请输入备注"
                />
              </Form.Item>


            </Form>
          </div>
        </div>

        <div className="ourCard">
          <div className="header">
            <div className="title">容器单位换算</div>
          </div>
          <div className="content">
            <p>在这里选择容器 设置换算关系</p>
          </div>
        </div>
        <div className="ourCard">
          <div className="header">
            <div className="title">容器单位换算</div>
          </div>
          <div className="content">
            <p>在这里选择容器 设置换算关系</p>
          </div>
        </div>
        <div className="ourCard">
          <div className="header">
            <div className="title">容器单位换算</div>
          </div>
          <div className="content">
            <p>在这里选择容器 设置换算关系</p>
          </div>
        </div>
        <div className="ourCard">
          <div className="header">
            <div className="title">容器单位换算</div>
          </div>
          <div className="content">
            <p>在这里选择容器 设置换算关系</p>
          </div>
        </div>

      </PageContainer>
    );
  }
}

export default CreateMat;
